<?php
/**
 * 后台登陆控制器。
 *
 * @author    Fairyin <fairyin@126.com>
 * @copyright © 2016 www.imcn.vip
 * @version   v1.0
 */

namespace App\Http\Controllers\Shadow;

use View;
use Config;
use Response;
use Redirect;
use App\Http\Model\User;
use Illuminate\Http\Request;

class LoginController extends ShadowController
{
    public function onGet()
    {
        if ($this->user) {
            return Redirect::to('/shadow/index');
        }
        setcookie('u', '', time() - 86400, '/', '.imcn.vip');
        $this->results['token'] = csrf_token();

        return View::make('shadow/login', $this->results);
    }
    
    public function onPost(Request $request)
    {
        $a_result = array();
        $s_account = $request->get('account', '');
        $s_pwd = $request->get('password', '');
        if ($s_account == '' || $s_pwd == '') {
            $a_result['reason'] = '请输入账号密码！';
            
            return $this->ajaxError($a_result);
        }
        $s_pwd = User::generatePassword($s_pwd);
        $o_user = User::where('nick_name', '=', $s_account)
            ->where('password', '=', $s_pwd)
            ->where('type', '=', 'manage')
            ->first();
        if (!count($o_user)) {
            $a_result['reason'] = '账号或密码输入错误！';
            
            return $this->ajaxError($a_result);
        }
        if ($o_user->status != User::STATUS_ENABLE) {
            $a_result['reason'] = '账号已被禁用！';
            
            return $this->ajaxError($a_result);
        }
        $s_token = $o_user->generateToken();
        if ($s_token == false) {
            $a_result['reason'] = '生成 token 失败！';
            
            return $this->ajaxError($a_result);
        }
        $a_result = array(
            'token' => $s_token
        );
        
        return $this->ajaxSuccess($a_result);
    }
}
